//! app 运行核心逻辑
//! 
//! app.rs
//! 
//! (RUST) alone
//! 
//! Create time: 2025-09-22		alone
//! Update time: 2025-09-30		alone
//! 

use std::{process::exit};

use anyhow::Ok;
use tracing::{info, error};

use crate::{common::{controller::Controller, pubsub::Subscribe, types::AppExitStatus, utils::Utils}, conf, core::data_controller::DataController, events::Events, logs, net::{net_manager::NetManager}};

#[derive(Debug, Clone)]
pub struct Application
{
	is_quit: bool,
	state: AppExitStatus,
	net_mgr: Option<NetManager>,
}

impl Application
{
	pub fn new() 
		-> Self
	{
		Self 
		{ 
			is_quit: false,
			state: AppExitStatus::Success,
			net_mgr: None
		}
	}

	pub async fn exec(&mut self) 
		-> anyhow::Result<()>
	{
		self.init().await;
		while !self.is_quit
		{
			// println!("Application::exec -> loop");
			Utils::sleep(2);
		}
		Ok(())
	}

	async fn init(&mut self)
	{
		// 初始化配置
		if let Err(e) = conf::init_config() 
		{
			println!("{e}");
			self.state = AppExitStatus::LoadingConfigFailed;
			self.quit();
		}

		// 初始化日志
		let conf = conf::config();
		logs::Logger::initialize(
			conf.logs.dir.clone().into(), 
			conf.logs.file_name.clone(),
			conf.logs.level.clone(),
		);
		info!("完成应用程序配置以及日志初始化。:)");

		// 初始化网络
		self.net_mgr = Some(NetManager::new(conf.clone()));
		if let Err(e) = self.net_mgr.as_ref().unwrap().initialize().await
		{
			error!("{e}");
			self.quit();
		}

		// 网络事件
		let app = self.clone();
		tokio::spawn(async move {
			app.net_event().await;
		});
		
	}

	fn quit(&mut self)
	{
		exit(self.state as i32)
	}

	async fn net_event(&self)
	{
		let mut tx = self.net_mgr.as_ref().unwrap().subscribe();
		while let Result::Ok(event) = tx.recv().await 
		{
			match event
			{
				Events::HandlerData(data_package) => 
				{
					info!("接收来自地址[{}]的发送的数据", data_package.socket.address());
					let controller = DataController::new(data_package);
					tokio::spawn(async move {
						controller.controller().await;
					});
				}
				_ => {}
			}
		}
	}
}